const baseurl = 'https://fc-mp-5632fc40-f047-42f3-8072-39dbd210a30e.next.bspapp.com';
function getUrlParam(name, urlStr = window.location.search.substr(1)) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var r = urlStr.match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}
function ajaxPost(params = {}) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    const url = baseurl + (params.url || '/human-admin/index/searchTalent');
    xhr.open('POST', url);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onload = function () {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(JSON.parse(xhr.response));
      } else {
        reject(new Error(xhr.statusText));
      }
    };
    xhr.onerror = function () {
      reject(new Error(xhr.statusText));
    };
    xhr.send(JSON.stringify(params.data));
  });
}
/**
 * 由月薪计算预估年薪
 * @param {*} salary 
 * @returns 年薪
 */
function calculateMoney(salary) {
				if (!salary.includes("·") && !salary.toLocaleLowerCase().includes("k"))
					return salary;
				const s = salary.split("·");
				var month = 12;
				if (s.length > 1) {
					const m = parseInt(s[1]);
					if (!isNaN(m)) {
						month = m;
					}
				}
				const money = parseInt(s[0].split("-").pop());
				if (isNaN(money)) {
					return salary;
				}
				return (money * month) / 10;
}
function saveLocal(key, value) {
  chrome.storage.local.set({
    [key]: value
  });
}

function removeLocal(key) {
  chrome.storage.local.remove(key);
}
async function getLocal(key) {
  const result = await chrome.storage.local.get([key]);
  return result[key];
}

function injectCustomJS(jsPath) {
  jsPath = jsPath || 'js/fetch.js';
  var temp = document.createElement('script');
  temp.setAttribute('type', 'text/javascript');
  temp.src = chrome.runtime.getURL(jsPath);
  temp.onload = function () {
    this.remove(); //执行完移除
  };
  document.body.appendChild(temp);
}

function getTodayCount() {
  const month = new Date().getMonth() + 1;
  const day = new Date().getDate();
  const date = `${month}${day}`;
  for (let key in localStorage) {
    if (key.includes('todayCount')) {
      if (!key.includes(date)) {
        localStorage.removeItem(key);
      }
    }
  }
  const todayCount = localStorage.getItem('todayCount' + date);
  if (!todayCount) {
    const count = 0;
    localStorage.setItem('todayCount' + date, count);
    return count;
  } else {
    return parseInt(todayCount);
  }
}

function setTodayCount(count) {
  const month = new Date().getMonth() + 1;
  const day = new Date().getDate();
  const date = `${month}${day}`;
  localStorage.setItem('todayCount' + date, count);
}
/****************************************************/
/*********************************/
const resumeUtils = {
  grabVal: 0, //当前抓取页面的结构类型
  sleep(time = 0) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, time);
    });
  },
  random(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
  },
  getSite() {
    const href = window.location.href;
    if (href.includes('liepin')) {
      return 'liepin';
    } else if (href.includes('maimai')) {
      return 'maimai';
    } else if (href.includes('zhaopin')) {
      return 'zhaopin';
    } else if (href.includes('zhipin')) {
      return 'zhipin';
    } else {
      return false;
    }
  },
  async postUserInfo(data) {
    //console.log("发送初始化信息：", { ...data, type: "init" });
    chrome.runtime.sendMessage(
      {
        ...data,
        type: 'init'
      },
      (response) => {
        if (response.code == 200) {
          console.log('查找成功222：', response);
          resumeUtils.userInfo = response.user;
          resumeUtils.initGrab();
        } else {
          resumeUtils.initGrab();
          //console.log('未查找到用户信息，查询失败', response);
        }
      }
    );
  },
  async initGrab() {
    const that = this;
    this.jobList = [];
    const site = resumeUtils.getSite();
    this.site = site;
    this.grabCount = this.grabCount || 0;
    await this.sleep(1000);
    if (site == 'liepin') {
      if ($('#resume-detail-single').length) {
        this.grabVal = 1; //猎聘抓取简历
        this.bindGrabEvt();
      } else if ($('.search-area .search-auto-complete-box').length) {
        this.grabVal = 3; //批量抓取简历
        const batchButton = `<button id="batchBtn" class="ant-btn ant-btn-danger search-btn" style="margin-left:5px;">开启检索</button>`;
        $('.search-area .search-auto-complete-box').append(batchButton);
        this.bindGrabEvt();
      } else if ($('.recruiter-container').length) {
        //当前是职位详情页
        this.grabVal = 7; //猎聘职位详情页抓取简历
        this.bindGrabEvt();
      } else {
        console.info('查找列表失败', this.grabCount, $('.recruiter-container').length);
        this.grabCount++;
        if (this.grabCount < 3) {
          await this.sleep(500);
          this.initGrab();
        } else {
          this.bindGrabEvt();
          this.grabCount = 0;
        }
      }
    } else if (site == 'maimai') {
      if ($('.PCcontainer .PCcontent .contact_detail_info').length) {
        this.grabVal = 2;
        this.bindGrabEvt();
      } else {
        //console.info("查找列表失败", this.grabCount);
        this.grabCount++;
        if (this.grabCount < 3) {
          await this.sleep(500);
          this.initGrab();
        } else {
          this.bindGrabEvt();
          this.grabCount = 0;
        }
      }
    } else if (site == 'zhaopin') {
      if ($('.resume-detail').length) {
        this.grabVal = 4;
        this.bindGrabEvt();
      } else if ($('.search-resume .keyword-search-wrapper').length) {
        this.grabVal = 6; //智联简历列表页面
        this.bindGrabEvt();
      } else {
        //console.info("查找列表失败", this.grabCount);
        this.grabCount++;
        if (this.grabCount < 3) {
          await this.sleep(500);
          this.initGrab();
        } else {
          this.bindGrabEvt();
          this.grabCount = 0;
        }
      }
    } else if (site == 'zhipin') {
      await this.sleep(1000);
      this.grabVal = 5; //boss抓取简历
      this.bindGrabEvt();
      /***监听全局切换事件**/
      $('.side-wrap .menu-list').off('click', '>dl');
      $('.side-wrap .menu-list').on('click', '>dl', function () {
        that.closeResume();
        const className = $(this).attr('class');
        that.bindBossChangeEvt(className);
      });
      this.bindBossChangeEvt();
      /********************/
    }
  },
  async bindBossChangeEvt(from) {
    await this.sleep(1000);
    let content;
    if (from) {
      const frame = from.includes('search') ? 'searchFrame' : 'recommendFrame';
      content = document.querySelectorAll(`iframe[name="${frame}"]`)[0]?.contentDocument;
    } else {
      content = document.querySelectorAll(`iframe`)[0]?.contentDocument;
    }
    const wrap = content?.querySelector('#container');
    /*关联查询重复 START*/
    $('body').off('click', '.system-repete');
    $('body').on('click', '.system-repete', (evt) => {
      this.post2BossPop(resumeUtils.bossTalent);
    });
    $(content).off('click', '.system-repete');
    $(content).on('click', '.system-repete', (evt) => {
      this.post2BossPop(resumeUtils.bossTalent);
    });
    /*推荐、新牛人切换*/
    // $(wrap).off('click','.tab-list .tab-item');
    // $(wrap).on('click','.tab-list .tab-item',async ()=>{
    // 	 await this.sleep(1000);
    // 	 this.bindBossChangeEvt();
    // });
    //console.log('推荐牛人：',$(wrap).find('ul .card-inner').length,$(wrap).find('.recommend-card-list>li').length)
    /***推荐牛人 START**/
    $(wrap).off('click', 'ul .card-inner');
    $(wrap).on('click', 'ul .card-inner', async (evt) => {
      const target = $(evt.currentTarget);
      const data = target.data();

      await this.sleep(500);
      if ($('.resumeGreet .btn-doc').length == 0 || $(content).find('.resumeGreet .btn-doc').length == 0) {
        await this.sleep(500);
      }
      if ($('.resumeGreet .btn-doc').length == 0 || $(content).find('.resumeGreet .btn-doc').length == 0) {
        await this.sleep(500);
      }
      const htmlStr = '<button type="button" class="btn-v2 system-repete" style="margin-top:10px;width:98%;">CMZC查重</button>';
      if ($('.resumeGreet .btn-doc').length) {
        $('.resumeGreet .btn-doc').append(htmlStr);
      } else {
        $(content).find('.resumeGreet .btn-doc').append(htmlStr);
      }
      /*************查询简历数据***************/
      /*************查询简历数据***************/
      /*************查询简历数据 START***************/

      await this.sleep(1000);
      const talent = this.getZPTalent(target);
      resumeUtils.bossTalent = Object.assign(talent, resumeUtils.bossTalentBaseData);
      //console.log('推荐牛人简历：',resumeUtils.bossTalent)
      /*************查询简历数据 END***************/
      //console.log('查询到推荐简历：', resumeUtils.bossTalent);
      //this.post2BossPop(talent);
    });
    /***搜索牛人 START**/
    $(wrap).off('click', '.geek-info-card>a');
    $(wrap).on('click', '.geek-info-card>a', async (evt) => {
      const target = $(evt.currentTarget);
      const data = target.data();
      await this.sleep(1000);
      $('.resume-footer-wrap .bubble-reference').prepend('<button class="btn system-repete" style="margin-right:10px;">CMZC查重</button>');
      //console.log('搜索牛人简历：',$('.resume-footer-wrap .bubble-reference').length)
      //this.post2BossPop(talent);
      /*************查询简历数据 START***************/

      await this.sleep(1000);
      const talent = this.getZPTalent2(target);
      resumeUtils.bossTalent = Object.assign(talent, resumeUtils.bossTalentBaseData);
      // console.log('搜索牛人简历：',resumeUtils.bossTalent)
      /*************查询简历数据 END***************/
      //console.log('查询到搜索简历：',talent)
      //this.post2BossPop(talent);
    });
    /*沟通牛人 start*/
    $('body').off('click', '.user-container .geek-item-wrap');
    $('body').on('click', '.user-container .geek-item-wrap', async (evt) => {
      this.closeResume();
      await this.sleep(500);
      const target = $(evt.currentTarget);
      const talent = await this.getZPTalent3(target);
      resumeUtils.bossTalent = talent;
      $('.conversation-operate .operate-exchange-left .system-repete').parent().remove();
      $('.conversation-operate .operate-exchange-left').append('<div class="operate-icon-item"><span class="operate-btn system-repete">CMZC查重</button></span>');
    });
    /**关闭弹窗取消显示简历关联**/
    $('body').off('click', '.dialog-wrap .boss-popup__close');
    $('body').on('click', '.dialog-wrap .boss-popup__close', (evt) => {
      this.closeResume();
    });
    $(content).off('click', '.dialog-wrap .boss-popup__close');
    $(content).on('click', '.dialog-wrap .boss-popup__close', (evt) => {
      this.closeResume();
    });
  },
  closeResume() {
    resumeUtils.bossTalentBaseData = null;
    window.postMessage(
      {
        type: 'close_resume'
      },
      '*'
    );
  },
  post2BossPop(userData) {
    //console.log('发送一次事件到resume弹窗');
    window.postMessage(
      {
        type: 'resume',
        data: {
          resume: userData,
          user: resumeUtils.userInfo,
          from: 'zhipin'
        }
      },
      '*'
    );
  },
  async bindGrabEvt() {
    const autoVal = await getLocal('autoVal');
    $('body').append(`<div id="resumeWraper"></div>`);
    console.log('注入成功，当前抓取类型：' + this.grabVal);
    /**********************************/
    const pictureVal = await getLocal('pictureVal');
    $('body').attr('data-picture', pictureVal);
    const userVal = await getLocal('userVal');
    $('body').attr('data-user', userVal);
    /* 注入JS */
    injectCustomJS('resume/js/bundle.js');
    setTimeout(() => {
      //console.error('简历抓取注入成功，当前抓取类型：',this.grabVal);
      if (this.grabVal == 1) {
        //liepin
        this.getLPResumeData();
        //检测简历是否为中文姓名
        this.checkFullName(true);
      } else if (this.grabVal == 2) {
        //maimai
        this.getMMResumeData();
      } else if (this.grabVal == 3) {
        this.bindBatchGrabEvt();
        this.checkTalentStatus();
      } else if (this.grabVal == 4) {
        this.getZLResumeData();
      } else if (this.grabVal == 5) {
        //BOSS
        console.log('BOSS 注入弹窗');
      } else if (this.grabVal == 6) {
        //智联招聘简历列表页面
        this.checkTalentStatus();
      } else if (this.grabVal == 7) {
        //猎聘职位页面抓取猎头职位详情
        this.getLTResumeData();
      } else if (this.grabVal == 0) {
        //猎聘简历详情，但是没匹配到简历
        if (autoVal && window.location.href.includes('/resume/showresumedetail')) {
          saveLocal('autoVal', '');
          this.sendCheckNextTalent({
            autoVal
          });
        }
        //智联卓聘简历详情，但是没匹配到简历
        if (autoVal && window.location.href.includes('/zphunter/resume/detail')) {
          saveLocal('autoVal', '');
          this.sendCheckNextTalent({
            autoVal
          });
        }
        //脉脉简历详情，但是没匹配到简历
        if (autoVal && window.location.href.includes('/profile/detail')) {
          saveLocal('autoVal', '');
          this.sendCheckNextTalent({
            autoVal
          });
        }
      }
      /**************************/
    });
  },
  async checkTalentStatus() {
    let that = this;
    let list;
    that.lastSearchKey = '';
    await that.sleep(1500);
    if (this.grabVal == 3) {
      list = $('.table-box .new-resume-card tr');
    } else if (this.grabVal == 6) {
      list = $('.candidate-list .candidate-info');
    }

    list.each(function (index, talent) {
      $(talent).removeClass('repeat-resume');
    });
    let resumes = [];
    if (this.grabVal == 3) {
      resumes = that.getLpTalentsList();
    } else if (this.grabVal == 6) {
      resumes = that.getZLTalentsList();
    }
    const isLast = $('.ant-pagination-item-active+li').hasClass('ant-pagination-disabled');
    const mutile = $('.ant-pagination').length > 0;
    if ((mutile || list.length == 0) && !isLast && ((that.grabVal == 3 && list.length < 30) || (that.grabVal == 6 && list.length < 10))) {
      await that.sleep(200);
      return that.checkTalentStatus();
    }
    // const nowKey = that.getSingleKey(resumes);
    // if(!that.lastKey||nowKey!=that.lastKey&&((that.grabVal == 3&&resumes.length<30)||(that.grabVal == 6&&resumes.length<10))){
    //   that.lastKey = nowKey;
    //   await that.sleep(500);
    //   return that.checkTalentStatus();
    // }
    /************************************/
    console.log('获取到简历列表：', resumes);
    const curKey = that.getSingleKey(resumes);
    //console.info(curKey,that.lastSearchKey);
    if (curKey == that.lastSearchKey) return;
    that.lastSearchKey = curKey;
    $('.resume_flag').remove();
    const justSelf = localStorage.getItem('justself'); //是否仅自己
    if ($('.without-repeat').length == 0) {
      $('.condition-tags-wrapper,.search-suck-quick-filter').prepend('<span class="without-self"><input class="self" type="checkbox"/>仅自己</span>');
      $('.condition-tags-wrapper,.search-suck-quick-filter').prepend('<span class="ant-tag without-repeat loading"><em></em>CMZC去重</span>');
      //console.error('执行插入',$('.search-suck-quick-filter').length)
      const hasClose = localStorage.getItem('cmzcclose');
      if (hasClose) {
        $('.without-repeat').addClass('close');
      }
      if (justSelf=='true') {
        $('.without-self input').prop('checked',true);
      }
    } else {
      $('.without-repeat').addClass('loading');
    }
    //console.log(resumeUtils.userInfo,333222)
    const response = await ajaxPost({
      url: '/human-admin/index/repeats',
      data: {
        from: that.site,
        self: justSelf=='true'?1:0,
        user_id: resumeUtils.userInfo?.user_id,
        resumes: resumes
      }
    });
    console.info('获取到查重：', response);
    if (response && response.length) {
      response.forEach((talent) => {
        const el = that.grabVal == 3 ? list.eq(talent.index).find('.detail-resume-card-wrap') : list.eq(talent.index);

        if (!talent.viewed) {
          const html = `<div class="resume_flag ant-btn-primary">` + `<span>姓名:${talent.name}</span>` + `<span>创建人:${talent.username}</span>` + `<span>创建时间:${talent.update_time}</span>` + `${talent.promot_list ? '<span>备注:' + talent.promot_list?.content + '</span>' : ''}` + `</div>`;
          el.addClass('repeat-resume').append(html);
        } else {
          const html = `<div class="resume_flag ant-btn-primary viewed">` + `<span>浏览人:${talent.username}</span>` + `<span>浏览时间:${talent.create_time}</span>` + `</div>`;
          el.addClass('repeat-viewed').append(html);
        }

        //console.log('简历查重：', talent.index, html);
      });
    } else {
    }
    $('.without-repeat').removeClass('loading');
    const isClose = $('.without-repeat').hasClass('close');
    if (isClose) {
      $('.repeat-resume,.repeat-viewed').addClass('close');
    } else {
      $('.repeat-resume,.repeat-viewed').removeClass('close');
    }

    /*绑定点击事件执行翻页监听*/
    $('body').off('click', '.without-repeat');
    $('body').on('click', '.without-repeat', function () {
      const isClose = $(this).hasClass('close');
      if (!isClose) {
        $('.repeat-resume,.repeat-viewed').addClass('close');
        $(this).addClass('close');
        localStorage.setItem('cmzcclose', true);
        console.log('关闭重复简历显示');
      } else {
        $('.repeat-resume,.repeat-viewed').removeClass('close');
        $(this).removeClass('close');
        localStorage.removeItem('cmzcclose');
        console.log('打开重复简历显示');
      }
    });
    /*仅自己点击事件*/
    $('body').off('change', '.without-self input');
    $('body').on('change', '.without-self input', function () {
        const checked = $(this).prop('checked');
        localStorage.setItem('justself', checked);
    });
    /*分页点击事件*/
    $('body').off('click', '.ant-pagination .ant-pagination-item');
    $('body').on('click', '.ant-pagination .ant-pagination-item', async (evt) => {
      if ($(evt.currentTarget).hasClass('readingend')) return false;
      $('.resume_flag').remove();
      $('.repeat-resume').removeClass('repeat-resume');
      $('.repeat-viewed').removeClass('repeat-viewed');
      await that.sleep(1000);
      that.checkTalentStatus();
    });
    $('body').off('click', '.search-button,.search-btn');
    $('body').on('click', '.search-button,.search-btn', async () => {
      $('.resume_flag').remove();
      $('.repeat-resume').removeClass('repeat-resume');
      $('.repeat-viewed').removeClass('repeat-viewed');
      await that.sleep(1000);
      that.checkTalentStatus();
    });
    if ($('.readingend').length == 0) {
      var pagination = $('.ant-pagination');
      const readingend = '<li class="ant-pagination-item readingend"><a>标记已阅</a></li>';
      if (pagination.length < 1) {
        //console.log('位置查找错误')
        pagination.append(readingend);
        $('.new-resume-card tfoot,.search-resume .candidate-list').append(readingend);
      } else {
        pagination.append(readingend);
      }
    }
    $('body').off('click', '.readingend');
    $('body').on('click', '.readingend', async () => {
      that.tagTalents(resumes);
    });
  },
  async tagTalents(resumes) {
    const that = this;
    const list = resumes.map((resume) => {
      return resume.name.substr(0, 1) + '-' + resume.school.substr(0, 4) + '-' + resume.special.substr(0, 4) + '-' + resume.company.substr(0, 4) + '-' + resume.job.substr(0, 4);
    });
    $('.readingend a').text('标记中···');
    $('.readingend').addClass('loading');
    const response = await ajaxPost({
      url: '/human-admin/index/tagtalents',
      data: {
        from: that.site,
        user_id: resumeUtils.userInfo?.user_id,
        resumes: list
      }
    });
    $('.readingend').removeClass('loading');
    $('.readingend a').text('标记' + response.data?.length + '条');
    setTimeout(() => {
      $('.readingend a').text('标记已阅');
    }, 2000);
  },
  getSingleKey(list = []) {
    if (list.length == 0) return '';
    return list[0].name + list[list.length - 1].name + '-' + list.length;
  },
  getLpTalentsList() {
    const talentList = [];
    const that = this;
    const list = $('.table-box .new-resume-card tr');
    list.each(function (index, talent) {
      const name = $(talent).find('.new-resume-personal .new-resume-personal-name em').text().trim();
      const sex = $(talent).find('.new-resume-personal .new-resume-personal-name svg circle').length == 1 ? '2' : '1';
      const age = $(talent).find('.new-resume-personal-detail .personal-detail-age').text();
      const talentObj = { index, name, sex };
      talentObj.born = new Date(String(new Date().getFullYear() - parseInt(age) - 1)).getTime();
      /*************/
      /*企业经历*/
      const company = $(talent).find('.new-resume-personal+div').children().eq(0).children('p:last-child').children('span').eq(-2).text().split('·');
      if (company.length < 2) {
        return true;
      }
      talentObj.company = company[0].trim();
      talentObj.job = company[1].trim();
      /*教育经历*/
      const educate = $(talent).find('.new-resume-personal+div').children().eq(1).children('p:last-child').children('span').eq(-2).text().split('·');
      if (educate.length < 3) {
        return true;
      }
      talentObj.school = educate[0].trim();
      talentObj.special = educate[1].trim();
      talentObj.degree = educate[2].trim();
      talentList.push(talentObj);
    });
    return talentList;
  },
  getZLTalentsList() {
    const talentList = [];
    const that = this;
    const list = $('.candidate-list .candidate-info');
    list.each(function (index, talent) {
      const name = $(talent).find('.candidate-name').text().trim();
      const sex = name.includes('先生') ? '1' : '2';
      const age = $(talent).find('.candidate-name+div').children('span').eq(0).text();
      const talentObj = { index, name, sex };
      talentObj.born = new Date(String(new Date().getFullYear() - parseInt(age))).getTime();
      /*企业经历*/
      const company = $(talent).find('.company-experience:last-child');
      talentObj.company = company.children('div').eq(-2).text().trim();
      talentObj.job = company.children('div').eq(-1).text().trim();

      /*教育经历*/
      const contents = $(talent).find('.school-experience').children('div:eq(-2)').contents();
      talentObj.degree = contents.eq(0).text().trim().split('·')[0].trim();
      talentObj.school = contents.eq(1).text().trim();
      talentObj.special = $(talent).find('.school-experience').children('div:eq(-1)').text().trim();
      /*************/
      talentList.push(talentObj);
    });
    return talentList;
  },
  checkFullName(isinit = false) {
    let name;
    if (this.grabVal == 1) {
      name = $('#resume-detail-basic-info .name-box .name').attr('title');
    } else if (this.grabVal == 2) {
      //maimai
      name = $('.contact_detail_name span').text();
    }
    const chinese = /[\u4e00-\u9fa5]+/.test(name);
    // console.log('chinese:', this.chinese, chinese);
    /*******************************/
    if (!this.chinese && chinese && !isinit) {
      if (this.grabVal == 1) {
        //console.log('检测语言变化');
        this.getLPResumeData();
      }
    }
    /*******************************/
    if ((name && name.includes('*')) || !chinese) {
      setTimeout(() => {
        this.chinese = chinese;
        this.checkFullName();
      }, 1000);
    } else {
      $('body').attr('data-name', name);
    }
  },
  bindBatchGrabEvt() {
    localStorage.removeItem('nextTalent');
    this.todayCount = getTodayCount(); //今日检索详情数据量
    this.currentCount = 0; //本次检索的详情数据量
    $('#batchBtn').bind('click', async () => {
      if (!this.grabingStatus) {
        const response = await this.checkBatchResumeData();
        //console.info(response, 3333);
        if (!response) return;
        $('#batchBtn').html('正在检索');
      } else if (this.grabingStatus == 1) {
        this.grabingStatus = 2;
        $('#batchBtn').html('检索结束');
      } else if (this.grabingStatus == 2) {
        alert('检索已完成，请刷新后再试');
      }
    });
    window.addEventListener('storage', this.dealProcessOver);
  },
  storeBossData(data = {}) {
    const that = this;
    const abstractData = data.abstractData;
    // console.error('storeBossData:', abstractData);
    const baseInfo = abstractData?.baseInfo || abstractData;
    if (!baseInfo?.geekBaseInfo) return false;
    const { geekBaseInfo = {}, geekWorkExpList = [], geekEduExpList = [], geekProjExpList = [], showExpectPosition } = baseInfo;
    const userData = {
      geek: geekBaseInfo.userId || '',
      avatar: geekBaseInfo.tiny,
      name: geekBaseInfo.name,
      sex: geekBaseInfo.gender == 1 ? '1' : '2'
    };
    userData.companyList = geekWorkExpList.map((item) => {
      const time = this.getStartEndTime(item, { start: 'startYearMonStr', end: 'endYearMonStr' });
      return {
        name: that.getText(item.company),
        job: that.getText(item.positionName),
        time: time
      };
    });
    userData.educateList = geekEduExpList.map((item) => {
      const time = this.getStartEndTime(item, { start: 'startDateDesc', end: 'endDateDesc' });
      return {
        name: that.getText(item.school),
        special: that.getText(item.major),
        degree: that.getText(item.degreeName),
        time: time
      };
    });
    userData.projectList = geekProjExpList.map((item) => {
      const time = this.getStartEndTime(item, { start: 'startDateDesc', end: 'endDateDesc' });
      return {
        name: that.getText(item.name),
        level: that.getText(item.roleName),
        time: time
      };
    });
    const company = userData.companyList[0] || {};
    userData.job = company.job;
    userData.company = company.name;
    resumeUtils.bossTalentBaseData = userData;
  },
  getStartEndTime(item, { start, end }) {
    let startDate = '',
      endDate = '';
    if (item[start]) {
      startDate = new Date(item[start]).getTime();
    }
    if (item[end] && !item[end].includes('至今')) {
      endDate = new Date(item[end]).getTime();
    }
    return [startDate, endDate];
  },
  getText(text) {
    return $(`<div>${text}</div>`).text();
  },
  /**
   * BOSS 推荐牛人
   */
  getZPTalent(target) {
    const userData = {};
    const data = target.data();
    userData.geek = data.geek;
    userData.avatar = target.find('.avatar-wrap img').attr('src');
    userData.name = target.find('.name-wrap .name').text();
    const tags = [];
    if (target.find('.row.base-info').length) {
      target.find('.row.base-info .label-text').each(function () {
        var text = $(this).text().trim();
        text && tags.push(text);
      });
    } else {
      target
        .find('.row .base-info')
        .contents()
        .each(function () {
          if (this.nodeType === 3) {
            // 文本节点
            var text = $(this).text().trim();
            text && tags.push(text);
          }
        });
    }

    userData.sex = target.find('.gender').get(0).className.includes('iboss-icon_man') ? '1' : '2'; //性别
    userData.born = new Date(String(new Date().getFullYear() - parseInt(tags[0]))).getTime();
    userData.status = tags[3] || '';
    const tags2 = [];
    $(target)
      .find('.col-2 .row')
      .eq(2)
      .find('.join-text-wrap')
      .contents()
      .each(function () {
        if (this.nodeType === 3) {
          // 文本节点
          var text = $(this).text().trim();
          text && tags2.push(text);
        }
      });
    userData.target = [
      {
        city: tags2[0] || '',
        job: tags2[1] || '',
        salary: target.find('.salary-wrap').text()
      }
    ];
    userData.educateList = [];
    //教育经历
    $(target)
      .find('.edu-exps .timeline-item')
      .each((i, item) => {
        const times = [];
        $(item)
          .find('.time')
          .contents()
          .each(function () {
            if (this.nodeType === 3) {
              // 文本节点
              var text = $(this).text().trim();
              if (text) {
                text = isNaN(parseInt(text)) ? '' : new Date(text).getTime();
                times.push(text);
              }
            }
          });
        const edus = [];
        $(item)
          .find('.content')
          .contents()
          .each(function () {
            if (this.nodeType === 3) {
              // 文本节点
              var text = $(this).text().trim();
              text && edus.push(text);
            }
          });
        userData.educateList.push({
          time: times,
          name: edus[0],
          special: edus[1],
          degree: edus[2]
        });
      });
    //工作经历
    userData.companyList = [];
    $(target)
      .find('.work-exps .timeline-item')
      .each((i, item) => {
        const times = [];
        $(item)
          .find('.time')
          .contents()
          .each(function () {
            if (this.nodeType === 3) {
              // 文本节点
              var text = $(this).text().trim();
              if (text) {
                text = isNaN(parseInt(text)) ? '' : new Date(text).getTime();
                times.push(text);
              }
            }
          });
        const work = [];
        $(item)
          .find('.content')
          .contents()
          .each(function () {
            if (this.nodeType === 3) {
              // 文本节点
              var text = $(this).text().trim();
              text && work.push(text);
            }
          });
        userData.companyList.push({
          time: times,
          name: work[0],
          job: work[1]
        });
      });
    userData.company = userData.companyList[0]?.name;
    userData.job = userData.companyList[0]?.job;
    userData.evaluation = $(target).find('.col-2 .row').eq(3).find('.content').text();
    userData.tags = [];
    $(target)
      .find('.col-2 .tags .tags-wrap .tag-item')
      .each((i, item) => {
        userData.tags.push(item.innerHTML);
      });
    // console.error('获取333：', userData)
    return userData;
  },
  getZPTalent2(target) {
    const userData = {};
    const data = target.data();
    userData.geek = data.geek;
    userData.avatar = target.find('.avatar-box img').attr('src');
    userData.name = target.find('.name .name-label').text();
    const tags = [];
    target.find('.info-labels .label-text').each(function () {
      var text = $(this).text().trim();
      text && tags.push(text);
    });
    userData.sex = target.find('.avatar-box i').get(0).className.includes('iboss-icon_man') ? '1' : '2'; //性别
    userData.born = new Date(String(new Date().getFullYear() - parseInt(tags[0]))).getTime();
    userData.status = tags[3] || '';
    const tags2 = [];
    $(target)
      .find('.geek-words-edus .work-exp-box')
      .eq(0)
      .find('.render-two')
      .each(function () {
        var text = $(this).text().trim();
        text && tags2.push(text);
      });
    userData.target = [
      {
        city: tags2[0] || '',
        job: tags2[1] || '',
        salary: tags[4]
      }
    ];
    userData.educateList = [];
    //教育经历
    $(target)
      .find('.geek-words-edus .edu-exp-box li')
      .each((i, item) => {
        const times = [];
        const edus = [];
        $(item)
          .find('.render-two')
          .each(function () {
            var text = $(this).text().trim();
            text && edus.push(text);
          });
        userData.educateList.push({
          time: times,
          name: edus[0],
          special: edus[1],
          degree: tags[2]
        });
      });
    //工作经历
    userData.companyList = [];
    $(target)
      .find('.geek-words-edus .work-exp-box')
      .eq(1)
      .find('li')
      .each((i, item) => {
        const times = [];
        const work = [];
        $(item)
          .find('.render-two')
          .each(function () {
            var text = $(this).text().trim();
            text && work.push(text);
          });
        userData.companyList.push({
          time: times,
          name: work[0],
          job: work[1]
        });
      });
    userData.company = userData.companyList[0]?.name;
    userData.job = userData.companyList[0]?.job;
    userData.evaluation = $(target).find('.geek-info-basic .info-detail').text();
    userData.tags = [];
    return userData;
  },
  /**
   * BOSS 搜索牛人
   */
  async getZPTalent2BACK(target) {
    await this.sleep(1000);
    const userData = {};
    const wrap = $('.resume-detail-wrap');
    const data = wrap.data('relatedinfo');
    userData.avatar = wrap.find('.avatar-wrap img').data('large');
    userData.name = wrap.find('.name .geek-name').text().trim();
    userData.sex = wrap.find('.name .gender').get(0).className.includes('iboss-icon_man') ? '1' : '2'; //性别
    const tags = [];
    wrap.find('.geek-info-base .info-labels span').each(function () {
      tags.push($(this).text());
    });
    userData.born = new Date(String(new Date().getFullYear() - parseInt(tags[0]))).getTime(); //出生年月
    userData.status = tags[3] || ''; //求职状态
    userData.evaluation = wrap.find('.selfDescription').text();
    const tags2 = [];
    wrap.find('.geek-expect-wrap span').each(function () {
      tags2.push($(this).text());
    });
    userData.target = [
      {
        city: tags2[0] || '',
        job: tags2[1] || '',
        industry: tags2[2] || '',
        salary: tags2[3] || ''
      }
    ];
    /**工作经历**/
    userData.companyList = [];
    wrap.find('.geek-work-experience-wrap .work-wrap').each(function () {
      const company = {};
      company.name = $(this).find('.company-name').text();
      company.job = $(this).find('.position .h').text();
      company.department = $(this).find('.position span:eq(1)').text().replace('·', '').trim();
      company.time = $(this)
        .find('.name-wrap .period')
        .text()
        .split('-')
        .map((text) => {
          if (!text.trim() || text.includes('至今')) return '';
          return new Date(text.trim()).getTime();
        });
      $(this)
        .find('.item-wrap')
        .each(function () {
          const text = $(this).find('.item-title').text();
          if (text.includes('业绩')) {
            company.achive = $(this).find('.item-content').html();
          } else {
            company.work = $(this).find('.item-content').html();
          }
          $(this)
            .find('.tags>span')
            .each(function () {
              if (!company.tags) {
                company.tags = [];
              }
              company.tags.push($(this).text());
            });
        });
      userData.companyList.push(company);
    });
    userData.company = userData.companyList[0].name;
    userData.job = userData.companyList[0].job;
    /*项目经历 */
    userData.projectList = [];
    wrap.find('.geek-project-experience-wrap .project-wrap').each(function () {
      const project = {};
      $(this)
        .find('.name-wrap .name span')
        .each(function (i) {
          if (i == 0) project.name = $(this).text();
          if (i == 1) project.level = $(this).text();
        });
      project.time = $(this)
        .find('.name-wrap .period')
        .text()
        .split('-')
        .map((text) => {
          if (!text.trim() || text.includes('至今')) return '';
          return new Date(text.trim()).getTime();
        });
      $(this)
        .find('.item-wrap')
        .each(function () {
          const text = $(this).find('.item-title').text();
          if (text.includes('业绩')) {
            project.achive = $(this).find('.item-content').html();
          } else {
            project.desc = $(this).find('.item-content').html();
          }
        });
      userData.projectList.push(project);
    });
    /**教育经历 */
    userData.educateList = [];
    wrap.find('.geek-education-experience-wrap .edu-wrap').each(function () {
      const educate = {};
      $(this)
        .find('.name-wrap .school-name-wrap span')
        .each(function (i) {
          if (i == 0) educate.name = $(this).text();
          if (i == 1) educate.special = $(this).text();
          if (i == 2) educate.degree = $(this).text();
        });
      educate.time = $(this)
        .find('.name-wrap .period')
        .text()
        .split('-')
        .map((text) => {
          if (!text.trim() || text.includes('至今')) return '';
          return new Date(text.trim()).getTime();
        });
      educate.tags = [];
      $(this)
        .find('.tags>span')
        .each(function () {
          educate.tags.push($(this).text());
        });
      userData.educateList.push(educate);
    });
    // console.log('简历数据：', userData, tags);
    return userData;
  },
  /* BOSS沟通 */
  async getZPTalent3(element) {
    const userData = {};
    const wrap = $('.conversation-box .conversation-main .base-info-content');
    userData.avatar = element.find('.figure .image-content img').attr('src');
    userData.name = wrap.find('.name-container .name-box').text();
	const xlinkhref = wrap.find('.base-name .boss-svg  use')?.attr('xlink:href');
	if(xlinkhref){
		userData.sex = xlinkhref.includes('women') ? '2' : '1'; //性别
	}
    wrap.find('.base-info-single-detial>div').each(function () {
      const text = $(this).text();
      if (text.includes('岁')) {
        userData.born = new Date(String(new Date().getFullYear() - parseInt(text))).getTime(); //出生年月
      }
    });
    const target = {};
    wrap
      .find('.position-content .position-item.expect .job')
      .contents()
      .each(function () {
        if (this.nodeType === 3) {
          // 文本节点
          var text = this.nodeValue.split('·');
          target.city = text[0].trim();
          target.job = text[1]?.trim();
        } else {
          var text = $(this).text().trim();
          target.salary = text;
        }
      });
    userData.target = [target];
    userData.companyList = [];
    userData.educateList = [];
    wrap.find('.experience-content.detail-list .work-content li').each(function (index, item) {
      const time = $('.experience-content.time-list .time-content li')
        .eq(index)
        .find('span.time')
        .text()
        .trim()
        .split('-')
        .map((text) => {
          if (!text.trim() || text.includes('至今')) return '';
          return new Date(text.trim()).getTime();
        });
      const ischool = $(this).find('svg.shool').length;
      if (ischool) {
        const educate = {};
        const texts = $(this).find('span.value').text().split('·');
        educate.name = texts[0]?.trim();
        educate.special = texts[1]?.trim();
        educate.degree = texts[2]?.trim();
        educate.time = time;
        userData.educateList.push(educate);
      } else {
        const texts = $(this).find('span.value').text().split('·');
        const company = {};
        company.name = texts[0]?.trim();
        company.job = texts[1]?.trim();
        company.time = time;
        userData.companyList.push(company);
      }
    });
    userData.company = userData.companyList[0].name;
    userData.job = userData.companyList[0].job;
    return userData;
  },
  async checkBatchResumeData(auto = false) {
    const that = this;
    const list = $('.table-box .new-resume-card tr');
    if (!list.length && auto) {
      return setTimeout(() => {
        this.checkBatchResumeData(auto);
      }, 1000);
    }
    if (!list.length && !auto) {
      alert('请选搜索简历再点击批量抓取');
      return false;
    }
    const pictureVal = await getLocal('pictureVal');
    if (!pictureVal) {
      alert('请导入候选人标签后再试');
      return false;
    }
    const pictureData = JSON.parse(pictureVal);
    const pictures = pictureData.picture;
    this.pictures = pictures;
    const talentList = [];
    list.each(function (index, talent) {
      const name = $(talent).find('.c-info-wrap .c-name').text();
      const age = $(talent).find('.c-info-wrap .c-info span').eq(0).html();
      const year = $(talent).find('.c-info-wrap .c-info span').eq(1).html();
      const educate = $(talent).find('.c-info-wrap .c-info span').eq(2).html();
      if (age && year && educate) {
        const talentObj = {
          index,
          name,
          age: parseInt(age?.match(/\d+/)),
          year: parseInt(year.match(/\d+/)),
          educate
        };
        const historys = [];
        let timeCount = 0;
        let average = 0;
        $(talent)
          .find('.c-edu-exp .c-edu-wrap:eq(0) p')
          .each((index2, item) => {
            const text1 = $(item).find('.c-sp').text();
            const job = text1.split('·')[1].trim();
            const text2 = $(item).find('.c-time').text();
            let timeStr = text2.match(/\((.+)\)/)?.[1];
            let time = 0;
            if (timeStr && timeStr.includes('年')) {
              const num = timeStr.split('年')[0];
              timeStr = timeStr.split('年')[1];
              time = parseInt(num);
            }
            if (timeStr && timeStr.includes('个月')) {
              const num = timeStr.split('个月')[0];
              time = time + parseInt(num) / 12;
            }
            timeCount += time;
            historys.push({
              job,
              time: time.toFixed(1)
            });
            average = timeCount / historys.length;
          });
        talentObj.average = average;
        talentObj.historys = historys;
        talentList.push(talentObj);
      }
    });
    /**********************************/
    /**********************************/
    /**********************************/
    const productObj =
      pictures.find((picture) => {
        return picture.key == 'product' || picture.key == 'product2';
      }) || {}; //产品
    const jobObj = pictures.find((item) => item.key == 'job');
    if (!jobObj) {
      alert('请导入职能标签后再试');
      return false;
    }
    const educateObj = pictures.find((item) => item.key == 'educate') || {};
    const educates = educateObj.children?.map((item) => item.name) || [];
    const stabileObj = pictures.find((item) => item.key == 'stabile') || {};
    // if (!stabileObj) {
    //   alert('请导入稳定性标签后再试');
    //   return false;
    // }
    const limitObj = pictures.find((item) => item.key == 'limit') || {};
    const jobs = jobObj.children.map((item) => item.name);
    const products = productObj.children.map((item) => item.name);
    const careerObj = pictures.find((item) => item.key == 'career') || {};
    const careers = careerObj.children?.[0]?.name?.replace('年', '')?.split('-') || [];
    const cMin = parseInt(careers[0]); //最短工作年限
    //const cMax = parseInt(careers[1]) || cMin;
    /************************/
    const stabiles = stabileObj?.children || [];
    const min = parseFloat(stabiles[0]?.name);
    const max = parseFloat(stabiles[1]?.name) || min;
    /************************/
    const limits = limitObj.children || [
      {
        name: '50条'
      }
    ];
    const limit = parseInt(limits[0].name);
    /*********************************************/
    const passList = talentList.filter((talent) => {
      let flag = false;
      //验证稳定性
      if (!isNaN(min) && talent.average < min) {
        return false;
      }
      //验证教育经历
      if (educates.length) {
        educates.forEach((educate) => {
          if (talent.educate.includes(educate)) {
            flag = true;
          }
        });
        if (!flag) return false;
      }
      flag = false;
      //验证工作经验
      if (cMin && !isNaN(cMin) && talent.year < cMin) {
        return false;
      }
      talent.historys.forEach((item) => {
        products.forEach((product) => {
          if (item.job.includes(product)) {
            flag = true;
            console.info(`${talent.name}:产品验证通过!`);
          }
        });
      });
      //如果产品验证不通过，验证最新一段经历职位是否包含职能标签
      if (!flag) {
        const jname = talent.historys[0]?.job;
        jobs.forEach((job) => {
          if (jname.includes(job)) {
            flag = true;
            console.info(`${talent.name}:最新职能验证通过!`);
          }
        });
      }
      return flag;
    });
    this.passList = passList;
    this.passCount = passList.length;
    this.grabingStatus = 1;
    $('#batchBtn').html('停止检索');
    console.info('本页符合条件的简历：', this.passList);
    this.viewTalentDetail(0);
    return true;
    //console.log(passList, talentList);
  },
  async viewTalentDetail(index = 0) {
    saveLocal('autoVal', index + 1);
    clearTimeout(this.timer2Next);
    if (!this.passList || this.passList.length == 0) {
      return this.currentBatchOver();
    }
    const passed = this.passList.shift();
    const pIndex = passed?.index;
    this.todayCount++;
    setTodayCount(this.todayCount);
    this.currentCount++;
    console.log(`当前页共${this.passCount}条简历符合,正在抓取第${this.passCount - this.passList.length}条,本页索引值:${pIndex},本次检索已完成${this.currentCount}条`);
    window.scrollTo({
      top: 300 + 135 * pIndex,
      behavior: 'smooth'
    });
    await this.sleep(index == 0 ? 2000 : 500);
    $('.table-box .new-resume-card tr').eq(pIndex).find('.detail-resume-card-wrap').trigger('click');
    this.timer2Next = setTimeout(() => {
      this.timerNextTalent();
    }, 16000);
  },
  /**
   * 超时，用于切换下一个简历详情查看
   */
  timerNextTalent() {
    localStorage.removeItem('nextTalent');
    if (this.grabingStatus == 1) {
      this.viewTalentDetail(1);
      console.log('超时，切换下一个简历详情查看');
    }
  },
  dealProcessOver(event) {
    const that = resumeUtils;
    /******************************/
    if (event.key === 'nextTalent' && event.newValue && that.grabingStatus == 1) {
      clearTimeout(this.timer2Next);
      const nextData = JSON.parse(event.newValue);
      const next = nextData.autoVal;
      localStorage.removeItem('nextTalent');
      console.log('接收到详情页返回：nextData', nextData);
      setTimeout(() => {
        if (that.site == 'zhaopin') {
          that.viewZLTalentDetail(next);
        } else if (that.site == 'liepin') {
          that.viewTalentDetail(next);
        } else if (that.site == 'maimai') {
          that.viewMMTalentDetail(next);
        }
      }, that.random(2000, 3000));
    }
  },
  async currentBatchOver(over = false) {
    const limitObj = this.pictures.find((item) => item.key == 'limit') || {};
    const limits = limitObj.children || [
      {
        name: '50条'
      }
    ];
    const limit = parseInt(limits[0].name);
    console.log('当前页批量抓取完成');
    if (this.currentCount && this.currentCount > limit) {
      this.grabingStatus = 2;
      $('#batchBtn').html('检索结束');
      console.log(`本次检索共抓取了${this.currentCount}条简历,已达${limit}上限`);
      return alert(`本次检索简历数已达上限${limit}条，请刷新或修改搜索条件后再试`);
    }
    if (this.grabingStatus != 1) {
      return false;
    }
    //翻下一页
    const active = $('.resume-list-pagebar .ant-pagination-item-active').next();
    if (!active || active?.length == 0 || active.hasClass('ant-pagination-next')) {
      this.grabingStatus = 2;
      console.log('当前已是最后一页，检索结束');
      $('#batchBtn').html('检索结束');
      return alert(`搜索结果已全部检索完成`);
    }

    window.scrollTo({
      top: this.random(1000, 2000),
      behavior: 'smooth'
    });
    await this.sleep(this.random(1000, 2500));
    window.scrollTo({
      top: this.random(2000, 3000),
      behavior: 'smooth'
    });
    await this.sleep(this.random(1000, 2000));
    active.trigger('click');
    await this.sleep(this.random(2000, 3000));
    this.checkBatchResumeData(true);
    // const todayCount = getTodayCount();
    // if (todayCount >= limit) {
    //   return alert('今日抓取已达上限，请明日再来');
    // }
  },
  async getMMResumeData() {
    console.log('开始抓取脉脉数据');
    const that = this;
    const autoVal = await getLocal('autoVal');
    //const company_id = await getLocal('company_id');
    const userData = {};
    userData.link = window.location.href;
    userData.avatar = $('#contact_avatar').attr('src'); //头像
    userData.name = $('.contact_detail_name span').text()?.trim(); //姓名
    if (autoVal && !userData.name) {
      saveLocal('autoVal', '');
      this.checkOverBool = true;
      this.sendCheckNextTalent({
        autoVal
      });
      return false;
    }
    let target_id;
    if (autoVal && userData.name) {
      target_id = await getLocal(userData.name + '_id');
      removeLocal(userData.name + '_id');
    }
    userData.job = $('.contact_detail_name+dd.text-muted span').text(); //职位
    userData.industry = $('.contact_detail_info  dd.m-t-2.text-muted').text().split(' ')[0]; //行业
    if (userData.industry.includes('影响')) {
      delete userData.industry;
    }
    const sexSrc = $('.contact_detail_name+dd.text-muted img').attr('src');
    if (sexSrc) {
      userData.sex = sexSrc.endsWith('28') ? '1' : '2';
    }
    userData.place = $('.contact_detail_connect_info .icon_address_gray').text();
    /* 工作经历 START */

    $('.PCcontent .panel-default').each((index, item) => {
      const title = $(item).find('.text-info span').text();
      if (title.includes('工作')) {
        const companyList = [];
        $(item)
          .find('.list-group  .exp-content')
          .each((index2, item2) => {
            const company = {
              name: $(item2).find('.info-section .info-text span').text().split('•')[0].trim(), //公司名称
              job: $(item2).find('.info-section .info-position').text() //职位
            };
            /***************************/
            const timeText = $(item2).find('.info-section .info-sub-title').text();
            let timeArr;
            if (timeText) {
              timeArr = this.parseTime(timeText, '(');
            }
            timeArr && (company.time = timeArr); //时间
            /***************************/
            const work = $(item2).find('.right-content .des-content').text(); //工作内容
            work && (company.work = work);
            /***************************/
            const taglist = [];
            $(item2)
              .find('.right-content .tag-list .exp_tag_text')
              .each((index3, item3) => {
                const tag = $(item3).text();
                taglist.push(tag);
              });
            if (taglist.length) {
              company.wtags = taglist;
              if (!userData.tags) {
                userData.wtags = taglist;
              } else {
                userData.wtags = [...userData.wtags, ...taglist];
              }
              //userData.tags = taglist;
            }
            /***************************/
            if (index2 == 0 && company.job) {
              userData.job = company.job;
              userData.company = company.name;
            }
            companyList.push(company);
          });
        userData.companyList = companyList;
      }
      if (title.includes('教育')) {
        const educateList = [];
        $(item)
          .find('.list-group  .exp-content')
          .each((index2, item2) => {
            const educate = {
              name: $(item2).find('.info-section .info-text span').text() //学校名称
            };
            const mixs = $(item2).find('.info-section .info-sub-title').text().split('，');
            educate.time = this.parseTime(mixs[0]);
            educate.special = mixs[1];
            educate.degree = mixs[2];
            educateList.push(educate);
          });
        userData.educateList = educateList;
      }
      if (title.includes('职业')) {
        const utags = [];
        $(item)
          .find('.list-group  .domain_skill_tag_main')
          .each((index2, item2) => {
            const tag = $(item2).find('span').text().split('·')[0].trim();
            utags.push(tag);
          });
        userData.tags = utags;
      }
      if (title.includes('看了') || title.includes('还没有')) {
        $(item).addClass('u-ignore');
      }
      /*自我评价 START*/
      if (title.includes('自我')) {
        userData.evaluation = $(item).find('.list-group .list-group-item>div').text();
      }
      /*自我评价 END*/
    });
    /* 工作经历 END */

    setTimeout(() => {
      html2canvas(document.querySelector('.PCcontainer .PCcontent>div:last-of-type'), {
        useCORS: true,
        scale: 1,
        ignoreElements: (ele) => {
          if ($(ele).hasClass('u-ignore')) {
            return true;
          }

          return false; //ele.offsetWidth === 0 || ele.offsetHeight === 0;
        }
      }).then((canvas) => {
        // document.body.appendChild(canvas);
        userData.extra = canvas.toDataURL('image/jpeg').replace(/^data:image\/jpeg;base64,/, '');
        //console.log('获取到用户信息：', userData);
        window.postMessage(
          {
            type: 'resume',
            data: {
              resume: userData,
              user: resumeUtils.userInfo,
              tid: target_id,
              force: autoVal && target_id,
              from: 'maimai'
            }
          },
          '*'
        );
      });
    }, 1000);
    /****************************************/
    if (autoVal) {
      saveLocal('autoVal', '');
      this.autoCheckZLTalent(userData, autoVal);
    } else {
      //const flag = await this.checkUserPassed(userData);
    }
  },
  async getZLResumeData() {
    const autoVal = await getLocal('autoVal');
    const company_id = await getLocal('company_id');
    const that = this;
    const userData = {};
    userData.link = window.location.href;
    const root = $('.resume-detail');
    userData.avatar = $('.personal-information .ant-avatar-image img').attr('src'); //头像
    userData.name = $('.resume-header-right .user-name-mess h6').text(); //姓名
    if (!userData.name) {
      return setTimeout(() => {
        that.getZLResumeData();
      }, 2000);
      return false;
    }
    if (autoVal && !userData.name) {
      saveLocal('autoVal', '');
      this.checkOverBool = true;
      this.sendCheckNextTalent({
        autoVal
      });
      return false;
    }
    const childNodes = $('.resume-header-right>p').get(0)?.childNodes || {}; //求职状态
    userData.sex = childNodes[0].nodeValue.includes('男') ? '1' : '2'; //性别
    userData.born = new Date(childNodes[2].innerText?.replace('年', '-')?.replace('月', '')).getTime(); //出生年份
    userData.status = childNodes[12].nodeValue?.trim(); //求职状态
    /*求职意向 START*/
    const targets = $('.desired-position .desired-position-item');
    if (targets && targets.length > 0) {
      userData.target = [];
      targets.each((index, target) => {
        userData.target.push({
          job: $(target).find('.job-type-name').text(),
          salary: $(target).find('.job-type-name+span').text().trim(),
          city: $(target).children().eq(1).find('span').eq(0).text().trim(),
          industry: $(target).children().eq(1).find('span').eq(1).text().trim()
        });
      });
    }
    /*求职意向 END*/
    /*教育经历 START*/
    const educateList = [];
    $('.education-experiences .education-experiences-item').each(function (index, item) {
      const name = $(item).find('.school-name').text().trim();
      if (!name) return;
      const tags = []; //学校标签
      $(item)
        .find('.school-name img.university-level-tag')
        .each((idx, tag) => {
          const src = $(tag).attr('src');
          if (src.includes('211')) {
            tags.push('211');
          } else if (src.includes('985')) {
            tags.push('985');
          }
        });
      const eduSpan = $(item).find('>div:eq(1) span');
      const timeArr = that.parseTime(eduSpan.eq(3).text().trim()); //教育时间
      const educate = {
        name, //学校名称
        special: eduSpan.eq(0).text().trim(), //专业名称
        degree: eduSpan.eq(1).text().trim(), //学位
        time: timeArr, //工作时间
        tags //学校标签
      };
      if (name) educateList.push(educate);
    });
    userData.educateList = educateList;
    /*教育经历 END*/
    /* 工作经历 START */
    const companyList = [];
    $('.work-experience-wrapper .work-experience-item').each(function (index, item) {
      let companyName = $(item).find('.company-info span:eq(0)').text().trim();
      let job = $(item).find('.company-info span:eq(1)').text().trim();
      if ($(item).find('.company-info span.keyword-highlight').length) {
        companyName = '';
      }
      if (!companyName) {
        const cStr = $(item).find('.company-info').text().trim();
        if (cStr.includes('公司')) {
          companyName = cStr.split('公司')[0] + '公司';
          job = cStr.split('公司')[1].trim();
        } else {
          companyName = cStr;
          job = cStr;
        }
      }
      if (index == 0) {
        userData.job = job;
        userData.company = companyName;
      }
      const timeStr = $(item).find('>div:eq(1) span:eq(0)').text().split('：')[1];
      const timeArr = that.parseTime(timeStr);
      // $(item)
      //   .find('.company-info span')
      //   .each(function (index2, item2) {
      //     const job = $(item2).text();
      //   });

      // let companyScale;
      //公司服务行业与服务 START
      const services = [];
      const service = $(item).find('>div:eq(2)').text().split('：')[1]?.trim();
      if (service) {
        services.push(service);
      }
      //公司服务行业与服务 END
      let work = $(item).find('>div.is-pre').html();
      if (!work) {
        const node = $(item).get(0)?.childNodes[3];
        if (node?.nodeType === 3) {
          work = node.nodeValue;
        }
      }
      const tags = []; //工作内容标签
      $(item)
        .find('.keyword-item')
        .each((index2, tag) => {
          const text = $(tag).text();
          tags.push(text);
        });
      const company = {
        name: companyName, //公司名称
        service: services,
        tags: tags,
        time: timeArr, //工作时间
        job: job, //职位
        work: work //工作内容
      };
      //if (!companyName.includes('未填写')) {
      companyList.push(company);
      //}
    });
    userData.companyList = companyList;
    /* 工作经历 END */
    /* 项目经历 START */
    const projectList = [];
    $('.project-experience-wrapper .project-experience-item').each((index, item) => {
      const timeStr = $(item).find('>div:eq(1)').text().split('（')[0];
      const timeArr = this.parseTime(timeStr);
      let work = $(item).find('>div.is-pre').html() || '';
      if (!work) {
        const nodes = $(item).get(0)?.childNodes;
        if (nodes?.length > 2) {
          nodes.forEach((node, idx) => {
            if (idx > 1) {
              work += node.textContent;
            }
          });
        }
      }
      const project = {
        name: $(item).find('.project-name').text(), //项目名称
        time: timeArr, //工作时间
        work: work //工作内容
      };
      projectList.push(project);
    });
    userData.projectList = projectList;
    /* 项目经历 END */
    /*自我评价 START*/
    userData.evaluation = $('.self-evaluate .is-pre').html();
    if (!userData.evaluation) {
      const node = $('.self-evaluate').get(0)?.childNodes[1];
      if (node?.nodeType === 3) {
        userData.evaluation = node.nodeValue;
      }
    }
    /*自我评价 END*/
    /*语言能力 START*/
    const language = [];
    $('.lanuage-wrapper .language').each((index, item) => {
      const text = $(item).find('.language-type').text();
      text && language.push(text);
    });
    userData.language = language;
    /*语言能力 END*/
    /*资格证书 START*/
    const credential = [];
    $('.achieve-certificate .achieve-certificate-item').each((index, item) => {
      let text = $(item).find('.achieve-certificate-name').text();
      if (!text) {
        text = $(item).find('>div:eq(0)').text();
      }
      text && credential.push(text);
    });
    userData.credential = credential;
    /*资格证书 END*/
    console.log('智联卓聘简历：', userData);
    setTimeout(() => {
      html2canvas(document.querySelector('#root .resume-detail'), {
        useCORS: true,
        scale: 1,
        ignoreElements: (ele) => {
          if ($(ele).hasClass('u-ignore')) {
            return true;
          }
          if (ele.tagName == 'IMG' && (ele.width == 0 || ele.height == 0)) {
            return true;
          }
          return false;
        }
      }).then((canvas) => {
        // document.body.appendChild(canvas);
        userData.extra = canvas.toDataURL('image/jpeg').replace(/^data:image\/jpeg;base64,/, '');
        //console.log('获取到用户信息：', userData);
        window.postMessage(
          {
            type: 'resume',
            data: {
              company_id,
              checkname: autoVal ? true : false,
              resume: userData,
              user: resumeUtils.userInfo,
              from: 'zhaopin'
            }
          },
          '*'
        );
      });
    }, 1500);
    /****************************************/
    if (autoVal) {
      saveLocal('autoVal', '');
      this.autoCheckZLTalent(userData, autoVal);
    } else {
      //const flag = await this.checkUserPassed(userData);
    }
  },
  async getLTResumeData() {
    const that = this;
    const userData = {};
    userData.link = window.location.href;
    userData.avatar = $('.user-photo .avator')?.attr('src'); //头像
    userData.name = $('.recruiter-container .name-box .name').text(); //姓名
    userData.job = $('.recruiter-container .title-box span:eq(0)').text(); //职位
    userData.company = $('.recruiter-container .title-box span:eq(1)')
      .text()
      .trim()
      .replace(/^\·+|\·+$/g, '')
      .trim(); //当前公司
    userData.companyList = [
      {
        name: userData.company,
        job: userData.job
      }
    ];
    const salary = $('.name-box .salary').text(); //期望薪资
    const city = $('.job-apply-content .job-properties span:eq(0)').text(); //城市
    const job = $('.job-apply-content .job-title').text();
    const desc = $('.job-intro-container .paragraph dd').html(); //职位详情描述
    const project = {
      time:[Date.now()],
      company:userData.company,
      name:  job + '（' + salary + '）'+'【' + city + '】', //项目名称
      desc: desc //项目描述
    };
    userData.projectList = [project];
    await that.sleep(500);
    const jobId = getUrlParam('jobId');
    if (jobId) {
      //console.log('发送岗位详情：',jobId);
      window.scrollTo({  //滚动页面
        top: document.body.scrollHeight,
        behavior: 'smooth'
      });
      await that.sleep(that.random(500, 1500));

      chrome.runtime.sendMessage(
        {
          data: {
            id: jobId,
            hunt:userData.company,
            desc
          },
          type: 'jobdetail'
        },
        async (response) => {
          if (response.code == 200) {
            await that.sleep(this.random(500, 1500));
            window.close();
          }
        }
      );
      return false;
    }
    
    window.postMessage(
      {
        type: 'resume',
        data: {
          resume: userData,
          user: resumeUtils.userInfo,
          from: 'lieqi'
        }
      },
      '*'
    );

    /******************/
    if($('.grab_btn').length){
      $('.grab_btn').remove();
    }
    $('.job-apply-content .name-box').append('<div class="grab_btn">导入到CMZC</div>');
    let companyTags = [],service,companyScale,headquarters;
    $('.company-other .label-box').each((index, item) =>{
       const label = $(item).find('.label').text();
       const text = $(item).find('.text').text();
       if(label.includes('行业')){
         service = text;
         companyTags.push(text);
       }else if(label.includes('规模')){
         companyScale = text;
         companyTags.push(text);
       }else if(label.includes('地址')){
         headquarters = text;
       }
    });
    const jobData = {
       name:job,
       salary:salary,
       salary_year:calculateMoney(salary),
       location:city,
       avatar:userData.avatar,
       companyName:userData.company,
       service:service,
       companyScale:companyScale,
       headquarters:headquarters,
       companyTags:companyTags,
       hr:userData.name,
       hrjob:userData.job,
       link:userData.link,
       description:desc
    }
    if(jobData.companyName.includes('人力')||jobData.hrjob.includes('猎头')){
      jobData.huntcompanyName = jobData.companyName;
    }
    $('.grab_btn').on('click',async function(){
        if($(this).hasClass('disabled'))return false;
        $(this).addClass('disabled');
        $('.grab_btn').text('导入中···');
        const response = await ajaxPost({
          url: '/human-admin/index/upload',
          data: {
            from: that.site,
            uid: resumeUtils.userInfo?.user_id,
            list: [jobData]
          }
        });
        if(response.code==200){
          $('.grab_btn').text('职位导入成功');
        }else{
          $('.grab_btn').text('职位导入失败');
        }
        console.log('拉取职位信息...',jobData);
    });
  },
  async getLPResumeData(force = false) {
    const autoVal = await getLocal('autoVal');
    const that = this;
    const userData = {};
    userData.link = window.location.href;
    userData.avatar = $('#resume-detail-basic-info .c-special-face')?.attr('src'); //头像
    userData.name = $('#resume-detail-basic-info .name-box .name')?.attr('title'); //姓名
    /*************************/

    /***********************跳过自动化验证************************************/
    if (autoVal && !userData.name) {
      saveLocal('autoVal', '');
      this.checkOverBool = true;
      this.sendCheckNextTalent({
        autoVal
      });
      return false;
    }
    /***********************************************************/
    userData.status = $('#resume-detail-basic-info .user-status-tag').text(); //求职状态
    const tags = $('#resume-detail-basic-info .basic-cont .sep-info').get(0).innerHTML.split('<i></i>');
    const tags2 = $('#resume-detail-basic-info .basic-cont .sep-info').get(1).innerHTML.split('<i></i>');
    userData.job = tags2[0]; //职位
    userData.company = tags2[1]; //当前公司
    userData.sex = tags.includes('男') ? '1' : '2'; //性别
    userData.born = new Date(String(new Date().getFullYear() - parseInt(tags[1]))).getTime(); //出生年份
    userData.tags = tags;
    /*求职意向 START*/
    const jobTarget = [];
    const jobCard = $('.job-card-right').get(0);
    if (jobCard) {
      jobCard.click();
      $('.want-job-list .job-card-left').each((index, item) => {
        jobTarget.push({
          job: $(item).find('.job-name').text(),
          salary: $(item).find('.salary').text(),
          city: $(item).find('.address').text(),
          industry: $(item).find('.industry-name span').text()
        });
      });
      $('.ant-modal-close').click();
      $('.ant-modal-root').css({
        opacity: 1
      });
    } else {
      jobTarget.push({
        job: $('#resume-detail-job-exp-info .left-wrap .title').text(),
        salary: $('#resume-detail-job-exp-info .left-wrap .salary').text(),
        city: $('#resume-detail-job-exp-info .left-wrap .dqname').text(),
        industry: $('#resume-detail-job-exp-info .left-wrap .lebels-wrap').text()
      });
    }
    userData.target = jobTarget;
    /*求职意向 END*/
    /* 工作经历 START */
    const companyList = [];
    $('.resume-detail-template-cont .rd-work-item-cont').each((index, item) => {
      let companyScale;
      const tags = [];
      $(item)
        .find('.rd-info-tpl-item-cont .tags-box .tag')
        .each((index, tag) => {
          const text = $(tag).text();
          if (text?.endsWith('人') || text?.endsWith('人以上')) {
            companyScale = text;
          } else if (!text.endsWith('轮') && !/融资|其他|上市|以上/g.test(text)) {
            tags.push(text);
          }
        });
      const timeStr = $(item).find('.rd-work-time').text();
      const timeArr = this.parseTime(timeStr);
      const otherData = this.getCompanyData(item);
      const company = {
        name: $(item).find('.rd-work-info-head .rd-work-comp h5').text(), //公司名称
        service: tags, //职位
        scale: companyScale, //公司规模
        time: timeArr, //工作时间
        job: $(item).find('.rd-info-tpl-item-cont .job-name').text(),
        ...otherData
      };
      companyList.push(company);
    });
    userData.companyList = companyList;
    /* 工作经历 END */
    /* 项目经历 START */
    const projectList = [];
    const otherLink = $('.rd-info-other-link').get(0);
    otherLink && otherLink.click();
    $('.resume-detail-project-info .rd-project-item-cont').each((index, item) => {
      const timeStr = $(item).find('.rd-project-time').text();
      const timeArr = this.parseTime(timeStr);
      const otherData = this.getProjectData(item);
      const project = {
        name: $(item).find('.rd-info-tpl-item-head .rd-project-name h5').text(), //项目名称
        time: timeArr, //工作时间
        ...otherData
      };
      projectList.push(project);
    });
    userData.projectList = projectList;
    /* 项目经历 END */
    /*教育经历 START*/
    const educateList = [];
    $('.resume-detail-edu-info .rd-edu-info-item').each((index, item) => {
      const timeStr = $(item).find('.school-time').text();
      const timeArr = this.parseTime(timeStr);
      const tags = [];
      $(item)
        .find('.edu-school-tags .tag-item')
        .each((idx, tag) => {
          tags.push($(tag).text());
        });
      educateList.push({
        name: $(item).find('.school-name').text(), //学校名称
        special: $(item).find('.school-special').text(), //专业名称
        degree: $(item).find('.school-degree').text(), //学位
        time: timeArr, //工作时间
        tags //学校标签
      });
    });
    userData.educateList = educateList;
    /*教育经历 END*/
    /*****************************************/
    /*资格证书 START*/
    const credential = [];
    $('.credential-tag-box .credential-tag').each((index, item) => {
      const text = $(item).text();
      credential.push(text);
    });
    userData.credential = credential;
    /*资格证书 END*/
    /*语言能力 START*/
    const language = [];
    $('.rd-lang-item .lang-name').each((index, item) => {
      const text = $(item).text();
      language.push(text);
    });
    userData.language = language;
    /*语言能力 END*/
    /*我的技能 START*/
    const skill = [];
    $('.skill-tag-box .skill-tag').each((index, item) => {
      const text = $(item).text();
      skill.push(text);
    });
    userData.skill = skill;
    /*我的技能 END*/

    /*自我评价 START*/
    userData.evaluation = $('#resume-detail-self-eva-info .resume-detail-template-cont div').html();
    //console.log('猎聘简历：', userData);
    /*自我评价 END*/
    resumeUtils.liepinTalent = userData;
    /*****************************************/
    //console.log(1212, tags);
    //console.log('获取到用户信息：', force, userData);
    // setTimeout(() => {
    // 	html2canvas(document.querySelector('#resume-detail-single'), {
    // 		useCORS: true,
    // 		scale: 1,
    // 		ignoreElements: (ele) => {
    // 			if ($(ele).hasClass('resume-operation-affixed-wrap')) {
    // 				return true;
    // 			}
    // 			return false; //ele.offsetWidth === 0 || ele.offsetHeight === 0;
    // 		}
    // 	}).then((canvas) => {
    // 		// document.body.appendChild(canvas);
    // 		userData.extra = canvas.toDataURL('image/jpeg').replace(
    // 			/^data:image\/jpeg;base64,/, '');
    // 		window.postMessage({
    // 				type: 'resume',
    // 				data: {
    // 					force,
    // 					resume: userData,
    // 					user: resumeUtils.userInfo,
    // 					from: 'liepin'
    // 				}
    // 			},
    // 			'*'
    // 		);
    // 	});
    // }, 1000);
    //if(force){
    this.post2LiePinPop(userData);
    //}
    /********************************************/

    if (autoVal) {
      saveLocal('autoVal', '');
      this.autoCheckTalent(userData, autoVal);
    } else {
      const flag = await this.checkUserPassed(userData);
    }

    return userData;
    /********************************************/
  },
  post2LiePinPop(data) {
    const userData = data || this.getLPResumeData();
    html2canvas(document.querySelector('#resume-detail-single'), {
      useCORS: true,
      scale: 1,
      ignoreElements: (ele) => {
        if ($(ele).hasClass('resume-operation-affixed-wrap')) {
          return true;
        }
        return false; //ele.offsetWidth === 0 || ele.offsetHeight === 0;
      }
    }).then((canvas) => {
      // document.body.appendChild(canvas);
      userData.extra = canvas.toDataURL('image/jpeg').replace(/^data:image\/jpeg;base64,/, '');
      window.postMessage(
        {
          type: 'resume',
          data: {
            resume: userData,
            user: resumeUtils.userInfo,
            from: 'liepin'
          }
        },
        '*'
      );
    });
  },
  /**
   * 自动检查猎聘人才信息
   *
   * @param userData 用户数据对象
   */
  async autoCheckTalent(userData, autoVal) {
    const timeGap = Date.now() - (this.lastCheckTime || 0);
    if (timeGap < 1000) return false;
    this.lastCheckTime = Date.now();
    /******************************/

    //检测通过强制推送到简历库
    const flag = await this.checkUserPassed(userData);
    if (flag) {
      //console.log('强制推送简历到系统', autoVal);
      this.getLPResumeData(true);
      await this.sleep(this.random(3000, 5000));
    } else {
      await this.sleep(this.random(1000, 3000));
    }
    window.scrollTo({
      top: this.random(1000, 3000),
      behavior: 'smooth'
    });
    await this.sleep(this.random(2000, 3000));
    window.scrollTo({
      top: this.random(4000, 6000),
      behavior: 'smooth'
    });
    await this.sleep(this.random(1000, 2000));
    //检测通过，调用 this.getLPResumeData(true);强制推送到简历库
    this.sendCheckNextTalent({
      flag,
      autoVal
    });
  },
  /**
   * 自动检查ZL人才信息
   *
   * @param userData 用户数据对象
   * @param autoVal 自动检测值
   * @returns 布尔值，表示是否检测通过
   */
  async autoCheckZLTalent(userData, autoVal) {
    const timeGap = Date.now() - (this.lastCheckTime || 0);
    if (timeGap < 1000) return false;
    this.lastCheckTime = Date.now();
    /******************************/
    await this.sleep(this.random(1000, 3000));
    window.scrollTo({
      top: this.random(500, 1000),
      behavior: 'smooth'
    });
    await this.sleep(this.random(1000, 2000));
    window.scrollTo({
      top: this.random(1000, 3000),
      behavior: 'smooth'
    });
    await this.sleep(this.random(1500, 2000));
    //检测通过，调用 this.getLPResumeData(true);强制推送到简历库
    this.sendCheckNextTalent({
      autoVal
    });
  },

  /**
   * 发送查阅下一条通知
   */
  async sendCheckNextTalent({ flag = false, autoVal }) {
    console.log('发送查阅下一条通知:', autoVal);
    localStorage.setItem(
      'nextTalent',
      JSON.stringify({
        autoVal
      })
    );
    await this.sleep(this.random(200, 500));
    this.timeCloseBool = true;
    if (this.checkOverBool) {
      return window.close();
    }
    // if(this.site=='zhaopin'){
    //   return window.close();
    // }
    // if (!flag) {
    //   //不符合直接关闭
    //   window.close();
    // } else {
    //   //符合条件，保留当前窗口打开状态
    // }
  },
  /**
   * 检查用户是否通过验证
   *
   */
  async checkUserPassed(userData) {
    const pictureVal = await getLocal('pictureVal');
    if (!pictureVal) return false;
    const pictureData = JSON.parse(pictureVal);
    const pictures = pictureData.picture;
    //console.log('开启检测当前简历！', pictures);
    /*****************************************/
    const pproduct =
      pictures.find((picture) => {
        return picture.key == 'product' || picture.key == 'product2';
      }) || {}; //产品
    const pjob = pictures.find((picture) => picture.key == 'job') || {}; //职能
    const pstabile = pictures.find((item) => item.key == 'stabile') || {}; //稳定性
    const psalary = pictures.find((item) => item.key == 'salary') || {}; //期望薪资
    const psalaryStr = psalary?.children?.[0]?.name || '';
    let salaryMax = 100;
    if (psalaryStr && psalaryStr.includes('-')) {
      salaryMax = parseFloat(psalaryStr.split('-')[1]);
    } else if (psalaryStr) {
      salaryMax = parseFloat(psalaryStr);
    }
    /************************/
    const stabiles = pstabile?.children || [];
    let minTime = parseFloat(stabiles[0]?.name); //最短稳定工作时间
    minTime = isNaN(minTime) ? 0 : minTime;
    let maxTime = parseFloat(stabiles[1]?.name) || minTime; //最长稳定工作时间
    maxTime = isNaN(maxTime) ? 0 : maxTime;
    /********************/
    const products =
      pproduct?.children?.map((item) => {
        return {
          name: item.name,
          match: 0
        };
      }) || [];
    const jobs =
      pjob?.children?.map((item) => {
        return {
          name: item.name,
          match: 0
        };
      }) || [];
    //console.info('jobs:', jobs);
    //console.info('products:', products);
    /**********工作经历匹配*******************************/
    let average = 0,
      timeCount = 0,
      productSuccess = false; //产品验证是否成功，即岗位包含产品关键词
    userData.companyList.forEach((company) => {
      const { time, job, work } = company;
      /*******************/
      if (time?.length == 1) {
        time.push(Date.now());
      }
      if (time?.length == 2) {
        timeCount += time[1] - time[0];
      }
      /**********产品匹配,工作经历职位包含产品，直接成功，不验证其他*********/
      products.forEach((item) => {
        if (job?.includes(item.name)) {
          item.match += 1;
          productSuccess = true;
          console.log(`★★★★★产品验证通过：工作经历:${company.name},职位:${job}，包含产品：${item.name}★★★★★`);
        }
      });
      /**********职能匹配，并且该经历下的岗位职责前50%包含产品*********/
      jobs.forEach((item) => {
        if (job?.includes(item.name)) {
          //如果岗位包含职能，则匹配成功
          item.match += 1;
          console.info(`★★★★★职能验证通过：工作经历:${company.name},职位:${job}，包含职能：${item.name},★★★★★`);
          /*查找岗位职责的50%是否包含产品*/
          products.forEach((item2) => {
            const index = work?.indexOf(item2.name);
            if (index != -1 && index / work?.length < 0.5) {
              item2.match += 1;
              productSuccess = true;
              console.log(`★★★★★产品验证通过：工作经历:${company.name},职位:${job}包含职能:${item.name},并且岗位职责包含产品：${item2.name}★★★★★`);
            }
          });
        }
      });
    });
    /***********如果产品没有成功，则验证项目名称是否包含产品关键词***********/
    if (!productSuccess) {
      userData.projectList.forEach((project) => {
        const { name, work, desc } = project;
        /**********产品匹配*********/
        products.forEach((item) => {
          if (name?.includes(item.name)) {
            item.match += 1;
            productSuccess = true;
            console.log(`★★★★★产品验证通过：项目名称:${name}包含产品：, ${item.name}★★★★★`);
          }
        });
      });
    }
    /**************如果产品没有成功，则验证个人评价是否包含产品关键词********/
    if (!productSuccess) {
      products.forEach((item) => {
        if (userData.evaluation?.includes(item.name)) {
          item.match += 1;
          productSuccess = true;
          console.log('★★★★★产品验证通过:个人评价包含产品：', item.name, '★★★★★');
        }
      });
    }
    /******************期望薪资验证*****************************/
    let salaryMatch = false;
    userData.target.forEach((target) => {
      let salary = target.salary?.replace('及以上', '').split('×')[0];
      if (salary?.includes('-')) {
        salary = parseFloat(salary.split('-')[0]);
      } else {
        salary = parseFloat(salary);
      }
      if (salary && salary < salaryMax) {
        //期望薪资最小值小于实际薪资最大值，通过验证
        salaryMatch = true;
        console.log('★★★★★期望薪资验证通过：', target.salary, '，实际待遇', psalaryStr, '★★★★★');
      }
    });
    if (!salaryMatch) {
      console.log('★★★★★期望薪资验证不通过：', userData.target, '，实际待遇', psalaryStr, '★★★★★');
      return false;
    }
    /**************稳定性验证************************/
    average = timeCount / (userData.companyList?.length * 30 * 24 * 3600 * 1000);
    average = parseInt(average / 12) + 0.084 * (average % 12);
    if (average < minTime) {
      //最短工作时间小于最短工作时间，不通过
      console.log('★★★★★稳定性验证不通过，平均：', average, '年 最小要求：', minTime, ' 年', '★★★★★');
      return false;
    } else {
      console.info(`★★★★★稳定性验证通过！稳定性：${average}年,最低要求:${minTime}年`, '★★★★★');
    }
    /***************职能验证 产品验证***********************/
    let jobMatch = false;
    //let productMatch = false;
    jobs.forEach((job) => {
      if (job.match > 0) {
        jobMatch = true;
      }
    });
    // if (!jobMatch) {
    //   //职能匹配不通过
    //   console.log('★★★★★★★★★★职能匹配不通过', jobs, '★★★★★★★★★★★★★★★');
    //   return false;
    // }
    // products.forEach((product) => {
    //   if (product.match > 0) {
    //     productMatch = true;
    //   }
    // });
    // if (!productMatch) {
    //   //产品匹配不通过
    //   console.log('★★★★★★★★★★★产品匹配不通过', products, '★★★★★★★★★★★★★★★');
    //   return false;
    // }
    if (!productSuccess) {
      console.log('★★★★★产品验证不通过', products, '在当前简历中岗位职责，项目名称，个人评价中未查找到产品关键词★★★★★');
      return false;
    }
    console.log('★★★★★★★★★★★★★当前简历验证通过★★★★★★★★★★★★★★★★');
    return true; //全部验证通过
  },
  getProjectData(el) {
    const odata = {};
    $(el)
      .find('.rd-info-col')
      .each((index, item) => {
        const title = $(item).find('.rd-info-col-title').text();
        const content = $(item).find('.rd-info-col-cont').text();
        if (title.includes('职务')) {
          odata.level = content;
        } else if (title.includes('公司')) {
          odata.company = content;
        } else if (title.includes('描述')) {
          odata.desc = content;
        } else if (title.includes('职责')) {
          odata.work = content;
        } else if (title.includes('业绩')) {
          odata.achive = content;
        }
      });
    return odata;
  },
  getCompanyData(el) {
    const odata = {};
    $(el)
      .find('.rd-info-col')
      .each((index, item) => {
        const title = $(item).find('.rd-info-col-title').text();
        const content = $(item).find('.rd-info-col-cont').text();
        if (title.includes('部门')) {
          odata.department = content;
        } else if (title.includes('下属')) {
          odata.lower = content;
        } else if (title.includes('汇报')) {
          odata.upper = content;
        } else if (title.includes('薪')) {
          odata.salary = content;
        } else if (title.includes('职位')) {
          odata.jtype = content;
        } else if (title.includes('职责')) {
          odata.work = content;
        } else if (title.includes('地点')) {
          odata.place = content;
        }
      });
    return odata;
  },
  parseTime(str, split = ',') {
    const list = str
      .split(split)[0]
      .replace(/[（）年]/g, '')
      .split('-');
    const time = [new Date(list[0]).getTime()];
    if (list[1] && !list[1].includes('至今')) {
      time.push(new Date(list[1]).getTime());
    }
    return time;
  },
  /**********************智联卓聘 批量检索开始 START*************************/
  async checkBatchZLResume(data) {
    localStorage.removeItem('nextTalent');
    //if(!company_id) return window.alert('公司id为空,无法关联简历');
    if (data && data.company_id) {
      saveLocal('company_id', data.company_id);
      this.company_id = data.company_id;
    }
    const list = $('.candidate-list .candidate-info');
    if (list.length == 0) return window.alert('当前页面无简历数据');
    this.passList = [];
    list.each((index) => {
      this.passList.push({
        index
      });
    });
    this.grabingStatus = 1;
    this.viewZLTalentDetail(0);
    window.addEventListener('storage', this.dealProcessOver);
    //console.log('开始验证：',company_id);
  },
  async viewZLTalentDetail() {
    clearTimeout(this.timer2Next);
    if (!this.passList || this.passList.length == 0) {
      return this.currentBatchZLOver();
    }
    if (this.grabingStatus == 2) {
      //手动结束抓取
      return this.currentBatchZLOver(true);
    }
    const passed = this.passList.shift();
    const pIndex = passed?.index;
    saveLocal('autoVal', pIndex + 1);
    window.scrollTo({
      top: 600 + 135 * pIndex,
      behavior: 'smooth'
    });
    await this.sleep(this.random(500, 1000));
    console.log('开始验证索引值：', pIndex);
    const name = $('.candidate-list .candidate-info').eq(pIndex).find('.candidate-name').text()?.trim();
    if (name) {
      const response = await ajaxPost({
        data: {
          name: name.substr(0, 1),
          company_id: this.company_id
        }
      });
      if (!response) {
        console.log('系统不存在:', name);
        return this.viewZLTalentDetail();
        //console.info('未查到候选人',name)
      } else {
        //console.info('查到候选人',name,response)
      }
    }
    $('.candidate-list .candidate-info').eq(pIndex).find('.info').trigger('click');
    this.timer2Next = setTimeout(() => {
      this.timerNextZLTalent();
    }, 16000);
  },
  timerNextZLTalent() {
    localStorage.removeItem('nextTalent');
    console.log('超时自动查看下一条简历');
    this.viewZLTalentDetail();
  },
  async currentBatchZLOver(over = false) {
    if (this.grabingStatus != 1 || over) {
      this.grabingStatus = 2;
      removeLocal('company_id');
      removeLocal('autoVal');
      return window.postMessage(
        {
          type: 'talent_match_over'
        },
        '*'
      );
    }
    //翻下一页
    const active = $('.ant-pagination .ant-pagination-item-active').next();
    if (!active || active?.length == 0 || active.hasClass('ant-pagination-next')) {
      this.grabingStatus = 2;
      return window.postMessage(
        {
          type: 'talent_match_over'
        },
        '*'
      );
    }
    window.scrollTo({
      top: this.random(1000, 2000),
      behavior: 'smooth'
    });
    await this.sleep(this.random(1200, 2000));
    window.scrollTo({
      top: this.random(2000, 3000),
      behavior: 'smooth'
    });
    await this.sleep(this.random(1200, 1500));
    active.trigger('click');
    await this.sleep(this.random(2000, 25000));
    this.checkBatchZLResume(true);
  },
  /**********************智联卓聘 批量检索结束 END*************************/
  /**********************脉脉 批量检索结束 START*************************/
  checkBatchMMResume(data) {
    localStorage.removeItem('nextTalent');
    //if(!company_id) return window.alert('公司id为空,无法关联简历');
    if (data && data.company_id) {
      saveLocal('company_id', data.company_id);
      this.company_id = data.company_id;
    }
    const list = $('.list-group>div');
    if (list.length == 0) {
      this.currentBatchMMOver(true);
      return window.alert('当前页面无简历数据');
    }
    this.startIndex = 0; //当前查阅索引值
    this.grabingStatus = 1;
    window.addEventListener('storage', this.dealProcessOver);
    this.startMMCheck();
  },
  checkBatchMMResume2(data) {
    localStorage.removeItem('nextTalent');
    //if(!company_id) return window.alert('公司id为空,无法关联简历');
    if (data && data.company_id) {
      saveLocal('company_id', data.company_id);
      this.company_id = data.company_id;
    }
    const list = $('[class^="talentContent___"] .talent-common-card');
    if (list.length == 0) {
      this.currentBatchMMOver(true);
      return window.alert('当前页面无简历数据');
    }
    this.grabingStatus = 1;
    window.addEventListener('storage', this.dealProcessOver);
    this.startMMCheck2();
  },
  startMMCheck() {
    const that = this;
    const start = this.startIndex;
    this.startIndex += 10;
    const end = this.startIndex;
    const list = $('.list-group>div');
    const names = [];
    //console.log('查询起始索引值:',start,'~',end);
    for (let i = start; i < end; i++) {
      //
      const name = list.eq(i).find('.media-body>div>div').eq(0).contents()?.[0]?.nodeValue?.trim();
      name &&
        names.push({
          index: i,
          name
        });
    }
    /********向后台发送要查阅的人员姓名信息**************/
    return window.postMessage(
      {
        type: 'talent_batch_match',
        data: {
          company_id: that.company_id,
          names
        }
      },
      '*'
    );
  },
  startMMCheck2() {
    const that = this;
    const list = $('[class^="talentContent___"] .talent-common-card');
    const names = [];
    //console.log('查询起始索引值:',start,'~',end);
    for (let i = 0; i < list.length; i++) {
      const name = list.eq(i).find('p.flex>span:eq(1)')?.text()?.trim();
      name &&
        names.push({
          index: i,
          name
        });
    }
    /********向后台发送要查阅的人员姓名信息**************/
    return window.postMessage(
      {
        type: 'talent_batch_match',
        data: {
          company_id: that.company_id,
          names
        }
      },
      '*'
    );
  },
  async currentBatchMMOver(over) {
    const that = this;
    if (this.grabingStatus != 1 || over) {
      this.grabingStatus = 2;
      removeLocal('company_id');
      removeLocal('autoVal');
      return window.postMessage(
        {
          type: 'talent_match_over'
        },
        '*'
      );
    }
    if (this.grabingStatus == 2) {
      return false;
    }
    //人才银行翻页搜索
    if (this.mmValue == 1) {
      const active = $('[class^="paginationCon"]>div[class^="current"]').next();
      if (!active || active?.length == 0 || active.attr('class')?.includes('nextPage')) {
        this.grabingStatus = 2;
        this.currentBatchMMOver(true);
        return false;
      }
      active.get(0).scrollIntoView({
        behavior: 'smooth'
      });
      await this.sleep(this.random(3000, 5000));
      active.trigger('click');
      await this.sleep(this.random(3000, 5000));
      that.startMMCheck2();
    }
    //搜索页翻下一页
    if (this.mmValue == 2) {
      const len1 = $('.list-group>div').length;
      window.scrollTo({
        top: document.body.scrollHeight,
        behavior: 'smooth'
      });
      let count = 0;
      const inter = setInterval(() => {
        const len2 = $('.list-group>div').length;
        if (len2 > len1) {
          clearInterval(inter);
          that.startMMCheck();
        } else if (count > 50) {
          clearInterval(inter);
          this.currentBatchMMOver(true);
          console.log('翻页失败，自动结束...');
        }
        if ($('.search-result-list>div div.cursor-pointer').length) {
          $('.search-result-list>div div.cursor-pointer').trigger('click');
        }
        count++;
      }, 200);
    }
  },

  async dealMMBatchSuccess({ list }) {
    console.log('系统接收到返回！！！', list);
    //return false;
    if (list?.length > 0) {
      this.passList = list;
      await this.sleep(this.random(1200, 3000));
      this.viewMMTalentDetail(0);
      return false;
    }
    if (this.mmValue == 1) {
      await this.sleep(this.random(1500, 3000));
      console.log('当前页批量查询完毕，未查到系统存在的简历...');
      this.currentBatchMMOver();
      return false;
    }
    //如果当前页面还有未查询的列表先去做查询
    if (this.mmValue == 2 && this.startIndex < $('.list-group>div').length - 1) {
      await this.sleep(this.random(1500, 3000));
      return this.startMMCheck();
    }

    console.log('未查到系统存在的简历，自动翻页查看更多...');
    window.scrollTo({
      top: document.body.scrollHeight - 500,
      behavior: 'smooth'
    });
    await this.sleep(this.random(4000, 8000));
    this.currentBatchMMOver();
  },
  async viewMMTalentDetail() {
    clearTimeout(this.timer3Next);
    const closeEle = $('.ant-drawer .ant-drawer-title .flex .mui-icon');
    if (closeEle.length) {
      await this.sleep(this.random(2000, 3000));
      closeEle.get(0).click();
      await this.sleep(this.random(2000, 3000));
    } else {
      await this.sleep(this.random(2000, 3000));
    }
    if (!this.passList || this.passList.length == 0) {
      return this.currentBatchMMOver();
    }
    if (this.grabingStatus == 2) {
      //手动结束抓取
      return this.currentBatchMMOver(true);
    }
    const passed = this.passList.shift();
    const pIndex = passed?.index;
    saveLocal('autoVal', pIndex + 1);
    saveLocal(passed.name + '_id', passed._id); //保存系统人才_id，方便后续操作
    console.log('当前正在查看简历：', passed);
    if (this.mmValue == 1) {
      //人才银行
      const ele = $('[class^="talentContent___"] .talent-common-card').eq(pIndex);
      ele.get(0).scrollIntoView({
        behavior: 'smooth'
      });
      await this.sleep(this.random(2000, 4000));
      //ele.find('.mui-popover-inner [class^="moreContainer___"]>div:last-child').trigger('click');
      ele.trigger('click');
      await this.sleep(this.random(3000, 5000));
      const detailEle = $('.ant-drawer .ant-drawer-title .mui-btn');
      detailEle && detailEle.trigger('click');
      //console.log('人才详情点击跳转...',ele,ele.find('.mui-popover-inner'))
    } else if (this.mmValue == 2) {
      const ele = $('.list-group>div').eq(pIndex);
      ele.get(0).scrollIntoView({
        behavior: 'smooth'
      });
      await this.sleep(this.random(2000, 3500));
      ele.find('.media-right button').trigger('click');
    }
    //console.log('开始验证索引值：', pIndex);

    this.timer3Next = setTimeout(() => {
      this.timerNextMMTalent();
    }, 15000);
  },
  timerNextMMTalent() {
    localStorage.removeItem('nextTalent');
    console.log('超时自动查看下一条简历');
    this.viewMMTalentDetail();
  },

  /**********************脉脉 批量检索结束 END*************************/
  /**
   * 启动监听器
   *
   * 为window对象添加一个事件监听器，监听message事件。当接收到消息时，根据消息的类型执行不同的操作。
   */
  startListener() {
    const that = this;
    window.addEventListener(
      'message',
      (e) => {
        if (!e.data || !e.data.type) return false;
        //console.log('resume.js收到消息：', e.data);
        switch (e.data.type) {
          case 'talent_match': //登录同步
            if (that.site == 'zhaopin') {
              that.checkBatchZLResume(e.data?.data);
            } else if (that.site == 'maimai') {
              const href = window.location.href;
              if (href.includes('/recruit/talents')) {
                that.mmValue = 1; //人才银行搜索页
                that.checkBatchMMResume2(e.data?.data);
              } else if (href.includes('/search_center')) {
                that.mmValue = 2; // 脉脉检索页
                that.checkBatchMMResume(e.data?.data);
              }
            }
            break;
          case 'stop_talent_match':
            saveLocal('company_id', '');
            that.grabingStatus = 2;
            break;
          case 'check_talent_end':
            that.checkOverBool = true;
            if (that.timeCloseBool) {
              window.close();
            }
            break;
          case 'talent_batch_match_success':
            that.dealMMBatchSuccess(e.data?.data);
            break;
          case 'IFRAME_DONE':
            that.storeBossData(e.data?.data);
            break;
          default:
            //console.log(e.data);
            break;
        }
      },
      false
    );
  }
};
/*******************************************************/
const resumeList = ['maimai', 'liepin', 'zhaopin', 'zhipin'];
$(() => {
  //console.log('初始化 content script');
  const site = resumeUtils.getSite();

  if (resumeList.includes(site)) {
    resumeUtils.postUserInfo({
      site
    });
    resumeUtils.startListener();
  }
});
